package com.waymap.utils.mq;


import java.util.HashMap;
import java.util.Map;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
import com.waymap.service.TransactionInventoryDetailsService;
import net.sf.json.JSONObject;
import org.reflections.util.Utils;
import org.scribe.model.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import com.waymap.common.Constant;
import com.waymap.domain.Accounts;
import com.waymap.service.SyncService;
import com.waymap.service.TransactionsService;
import com.waymap.utils.NSRestConnector;
import com.waymap.utils.StringUtil;

import net.sf.json.JSONArray;

/**
 * Created by tim on 2018/7/27.
 * 消费者
 */
@Component
public class MsgConsumer {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SyncService syncService;
    @Autowired
    private TransactionsService transactionsService;

    @Autowired
    private TransactionInventoryDetailsService transactionInventoryDetailsService;


    @JmsListener(destination = Constant.Queue_Name, containerFactory = "jmsQueueListener")
    @Async
    public void receiveQueue(TextMessage MessageText, Session session) throws JMSException {

        logger.info("Consumer收到的报文为:" + MessageText.getText().toString());
        MessageText.acknowledge();//消息确认
        try {
            if (!Utils.isEmpty(MessageText.getText().toString())) {
                String[] tranInfo = MessageText.getText().toString().split(":");
                if (tranInfo.length > 0) {
                    //    String transactionType = tranInfo[0];
                    String tranid = tranInfo[1];
                    String accountId = tranInfo[3];
                    Map<String, Object> param = new HashMap(16);
                    param.put("tranid", tranid);
                    param.put("accountId", accountId);
                    logger.info("******************MQ数据tranid*********************" + tranid);
                    Map tranVo = syncService.getTransactionInfo(tranid, accountId);
                    if (null != tranVo) {
                        /**发送封装好的数据**/
                        param.clear();
                        param.put("accountId", accountId);
                        Accounts accountInfo = transactionsService.getAccountInfo(param);
                        if (null != accountInfo) {
                            logger.info("******** start connect NS URL ********");
                            logger.info("******************MQ发送封装好的数据:" + tranVo.toString() + "*****************");
                            NSRestConnector connector = new NSRestConnector(accountInfo.getWms_url(), accountInfo.getTokenId(),
                                    accountInfo.getTokenSecret(), accountInfo.getConsumerKey(),
                                    accountInfo.getConsumerSecret(), accountInfo.getAccountId());
                            String questBody = JSONArray.fromObject(tranVo).getString(0);
                            logger.info("reqeust body::" + questBody);
                            Response rep = connector.callWithHttpPost(questBody);
                            if (null != rep && rep.getCode() == 200) {
                                logger.info("******************MQ数据发送成功*********************");
                                if (!StringUtil.isNullOrEmpty(tranid)) {
                                    param.clear();
                                    param.put("accountId", accountId);
                                    param.put("tranid", tranid);
                                    transactionsService.updateStatusByTranid(param);
                                    logger.info("***************更改transactions表sync_to_ns状态OK*************");
                                }
                                logger.info("***************消息手动签收*************");
                            } else {
                                logger.info("***************MQ数据发送失败*************");
                                Map map = (Map) JSONObject.fromObject(rep.getBody()).get("error");
                                param.clear();
                                param.put("accountId", accountId);
                                param.put("tranid", tranid);
                                param.put("errorReason", map.get("message").toString());
                                transactionsService.updateStatusByError(param);
                                logger.debug(rep.toString());
                            }
                        } else {
                            logger.info("***************查询数据账户accountInfo信息为空*************" + accountInfo);
                        }

                    } else {
                        logger.info("***************查询数据tranVo为空*************" + tranVo);
                    }
                }

            } else {
                logger.info("接收的消息为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("***************异常机制消息重发信息*************");
            //session.recover();// 此不可省略 重发信息使用
        }
    }

}
